import { Component, OnInit } from '@angular/core';
import { NavController, ModalController } from '@ionic/angular';
import { ActivatedRoute, Params } from '@angular/router';
import { AuthService } from 'src/app/services/auth.service';
import { ToastService } from 'src/app/providers/toast/toast.service';
import * as constants from '../../../providers/Constants'
import { OrderService } from 'src/app/services/order.service';
import { Storage } from 'src/app/providers/Storage';
import { OrderDialogComponent } from 'src/app/component/order-dialog/order-dialog.component';
import { NativeService } from 'src/app/providers/NativeService';
import { Helper } from 'src/app/providers/Helper';
import { Utils } from 'src/app/providers/Utils';
@Component({
  selector: 'app-order-create',
  templateUrl: './order-create.page.html',
  styleUrls: ['./order-create.page.scss'],
})
export class OrderCreatePage implements OnInit {
  addressList: any = {};
  goodsInfo: any = [];
  allPrice: number = 0;
  allPriceAcc: number = 0;
  noAddress: boolean = false;
  // addressList: any = {
  //   addressUserName:'',
  //   addressPhone:'',
  //   address:'',
  // };
  orderInfo: any = [];
  procPriceId: string = '';
  imageUrl: string = '';
  detailsType: number = 0;
  shoppingCart: number = 0;
  couponAccInfo: any = null;
  backCardInfo: any = {};

  cardList: any = [];
  isBackCard: boolean = false;
  remarks: string = '';
  expressFee: number = 0;
  isShoppingCart: boolean = false;
  constructor(private nav: NavController, private native: NativeService, private mHelper: Helper, private modalController: ModalController, private order: OrderService, private activeRoute: ActivatedRoute, private auth: AuthService, private toast: ToastService) {
    this.activeRoute.queryParams.subscribe((params: Params) => {
      if (params.shoppingCart) {

        this.isShoppingCart = true;
        this.shoppingCart = params.shoppingCart;
        this.goodsInfo = JSON.parse(params.goodsInfo);
        this.detailsType = params.detailsType;
        this.procPriceId = params.procPriceId;
      } else {
        if (params.goodsInfo) {
          this.goodsInfo[0] = JSON.parse(params.goodsInfo);
          this.detailsType = params.detailsType;
          this.procPriceId = params.procPriceId;
          console.log('===', this.goodsInfo);
        }
      }
      this.expressFee = isNaN(this.goodsInfo[0].expressFee) ? 0 : this.goodsInfo[0].expressFee / 100
      this.initCard();
      console.log('params.goodsInfo=', this.goodsInfo[0]);

    });
    this.imageUrl = order.getImageUrl()
    console.log('couponAccInfo======111==', this.couponAccInfo);
    Storage.sessionStorage.remove('couponAccInfo');//优惠卷
  }
  utilsCard(str) {
    if (str) {
      return Utils.utilsCard(str)
    }
    return '';

  }
  onClickItemBack() {
    this.nav.navigateForward('payment-type', {
      queryParams: {
        type: '1',
      }
    });
  }
  otherAdd() {
    this.nav.navigateForward('address', {
      queryParams: {
        type: 1,
      }
    })
  }
  cardInfo() {
    let cardInfo = Storage.sessionStorage.get('backCard');
    if (cardInfo) {
      this.isBackCard = true;
      this.backCardInfo = cardInfo;
    } else {
      this.isBackCard = false;
    }
  }

  solaImage(img) {
    return Utils.imageUrl(this.imageUrl, img);
  }

  initCard() {
    //查询银行卡列表
    this.order.getSelCard({}).subscribe(res => {
      // 保存成功返沪上一页，否则弹出提示框
      if (res.retCode == '000000') {
        console.log('银行卡列表', res);
        if (res.array.length > 0) {
          this.cardList = res.array;
          let isFast = false;
          for (let index = 0; index < this.cardList.length; index++) {
            const element = this.cardList[index];
            if (element.type == '0') {
              isFast = true;
              this.backCardInfo = element;
            }
          }
          this.isBackCard = true;
          if (!isFast) {
            this.backCardInfo = this.cardList[0]
          }
        } else {
          this.isBackCard = false;
        }
      } else if (constants.errCode[res.retCode]) {
        this.noAddress = true;
        if (constants.errCode[res.retCode] != '0') {
          this.toast.show(constants.errCode[res.retCode]);
        }
      } else if (res.retMsg) {
        this.noAddress = true;
        this.toast.show(res.retMsg);
      } else {
        this.toast.show("exception service routine");
      }
    });
  }


  ionViewDidEnter() {
    let address = Storage.sessionStorage.get('addressItem');
    if (address) {
      console.log('address', address);
      this.addressList = address;
      this.noAddress = false;
    }
    console.log('couponAccInfo======', this.couponAccInfo);
    this.couponAccInfo = Storage.sessionStorage.get('couponAccInfo');
    this.priceAll();
  }
  ngOnInit() {
    console.log('----------------9');
    Storage.sessionStorage.remove('addressItem')
    this.getData();

  }
  onDiscount() {
    this.nav.navigateForward('discount', {
      queryParams: {
        type: 1
      }
    });
  }
  AmountOfConversion(num: number) {
    return num / 100;
  }
  getData() {
    this.auth.queryAddress({}).subscribe(res => {
      // 保存成功返沪上一页，否则弹出提示框
      if (res.retCode == '000000') {
        this.noAddress = false;
        let addType = false;
        for (let index = 0; index < res.data.length; index++) {
          const element = res.data[index];
          if (element.addressType == 0) {
            this.addressList = element;
            addType = true;
          }
        }
        if (!addType) {
          if (res.data.length > 0) {
            this.noAddress = false;
            this.addressList = res.data[0]
          } else {
            this.noAddress = false;
          }
        }
      } else if (res.retCode == '000025') {
        this.addressList = {};
        this.noAddress = true;
      } else if (constants.errCode[res.retCode]) {
        this.noAddress = true;
        if (constants.errCode[res.retCode] != '0') {
          this.toast.show(constants.errCode[res.retCode]);
        }
      } else if (res.retMsg) {
        this.noAddress = true;
        this.toast.show(res.retMsg);
      } else {
        this.toast.show("exception service routine");
      }
    });
  }

  pay() {
    if (this.noAddress) {
      this.toast.show('Please select the address');
    } else if (!this.isBackCard) {
      this.toast.show('Please select bank card');
    } else {
      this.presentModal();
    }
  }
  price(type, index) {
    if (type == 0) {  //0 减
      if (this.goodsInfo[index].num <= 1) {
        return
      }
      this.allPrice = this.allPrice - this.AmountOfConversion(this.goodsInfo[index].procCashPrice)
      this.goodsInfo[index].num--
    } else {
      this.allPrice = this.allPrice + this.AmountOfConversion(this.goodsInfo[index].procCashPrice)

      this.goodsInfo[index].num++
    }
    console.log();
    this.allPrice = Number(Number(this.allPrice).toFixed(2));

  }

  priceAll() {
    this.allPrice = 0;
    for (let index = 0; index < this.goodsInfo.length; index++) {
      const element = this.goodsInfo[index];
      this.allPrice = this.allPrice + this.AmountOfConversion(this.goodsInfo[index].procCashPrice) * this.goodsInfo[index].num;
    }
    if (this.couponAccInfo) {
      this.allPrice = this.allPrice - this.AmountOfConversion(this.couponAccInfo.couponPrice)
    }
  }
  payConfirm() {
    console.log(this.goodsInfo);
    let dataArray = [];

    for (let index = 0; index < this.goodsInfo.length; index++) {
      const element = this.goodsInfo[index];
      console.log('element=', element);
      let shoppingCarId = '';
      if (this.isShoppingCart) {
        shoppingCarId = element.shoppingCarId
      }
      let data = {
        userAddressId: this.addressList.addressId,//地址id，
        merchCode: element.merchCode,
        num: element.num,//数量
        procAmt: this.allPrice,//价格，
        remarks: this.remarks,//备注，
        procPriceId: element.procPriceId,//价格id
        shoppingCarId: shoppingCarId,
        // procParts:this.goodsInfo[index].procParts,
        // procOrderType: '0',
        procStandards: element.size,
        // procColor: this.goodsInfo[0].procColor,
        procColor: element.color,
      }
      dataArray.push(data);
    }
    // if (this.detailsType == 4) {
    //   data.procPriceId = this.procPriceId
    // }
    // let d = [];
    // d[0] = data
    let couponAccId = ''
    if (this.couponAccInfo) {
      couponAccId = this.couponAccInfo.couponAccId;
    }
    this.order.markSureOrder({
      data: dataArray,
      couponAccId: couponAccId,
    }).subscribe(res => {
      // 保存成功返沪上一页，否则弹出提示框
      if (res.retCode == '000000') {
        // this.toast.show('Successful');
        this.orderPay(res.procOrderIds);
        // this.nav.navigateForward('pay-status', {
        //   queryParams: {
        //     status: 0
        //   }
        // });
      } else if (constants.errCode[res.retCode]) {
        if (constants.errCode[res.retCode] != '0') {
          this.toast.show(constants.errCode[res.retCode]);
        }
      } else if (res.retMsg) {
        this.toast.show(res.retMsg);
      } else {
        this.toast.show("exception service routine");
      }
    });
  }








  async presentModal() {
    const modal = await this.modalController.create({
      component: OrderDialogComponent,
      cssClass: 'order-component',
      showBackdrop: true,
      backdropDismiss: false,
      mode: 'md',
      componentProps: {
        // shopDetail: JSON.stringify(this.shopDetail),
        // isShow: this.isShow, shopId: this.shopId,
        // merchCode: this.merchCode,
        // type: type,
        // procList: this.procList
      }
    });

    await modal.present();
    //监听销毁的事件
    const { data } = await modal.onDidDismiss();
    console.log(data);
    this.payConfirm();


  }





  orderPay(procOrderIds) {
    let couponAccId = '';
    if (this.couponAccInfo) {
      couponAccId = this.couponAccInfo.couponAccId;
    }
    this.order.cashPlaceOrder({
      procOrderIds: procOrderIds,
      card: this.backCardInfo,
      cardId: this.backCardInfo.cardId,
      couponAccId: couponAccId,
      terminalId: this.native.getUuid(),
      terminalType: this.mHelper.isAndroid() ? 'android' : 'ios',
    }).subscribe(res => {
      // 保存成功返沪上一页，否则弹出提示框
      if (res.retCode == '000000') {
        // this.toast.show('Successful');
        this.nav.navigateBack('pay-status', {
          queryParams: {
            status: 0,
            allPrice: this.allPrice+this.expressFee,
            resInfo: JSON.stringify(res),
          }
        });
      } else if (constants.errCode[res.retCode]) {
        if (constants.errCode[res.retCode] != '0') {
          this.toast.show(constants.errCode[res.retCode]);
        }
      } else if (res.retMsg) {
        this.toast.show(res.retMsg);
      } else {
        this.toast.show("exception service routine");
      }
    });

  }






}
